<template>
    <div class="login">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-width="80px" class="login-form">
            <h3>用户登录</h3>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="loginForm.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleLogin">登录</el-button>
                <el-button @click="resetForm">重置</el-button>
                <router-link to="/register" class="router-link">
                    <el-button>注册</el-button>
                </router-link>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import axios from 'axios'
export default {
    data() {
        return {
            loginForm: {
                email: '',
                password: ''
            },
            loginRules: {
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { min: 3, max: 20, message: '邮箱长度在3到20个字符之间', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '密码长度在6到20个字符之间', trigger: 'blur' }
                ]
            },
        };
    },
    methods: {
        handleLogin() {
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    // 发送登录请求
                    axios.post('http://localhost:3000/api/login', {
                        email: this.loginForm.email,
                        password: this.loginForm.password
                    }).then(res => {
                        if (res.data.success) {
                            // 存储Token
                            localStorage.setItem('token', res.data.token);
                            this.$message.success('登录成功');
                            this.$router.push('/');
                        } else {
                            this.$message.error(res.data.message);
                        }
                    }).catch(error => {
                        console.log(error);
                        this.$message.error('登录失败，请检查邮箱或者密码是否错误');
                    });
                } else {
                    return false;
                }
            });
        },
        resetForm() {
            this.$refs.loginForm.resetFields();
        }
    }
};
</script>

<style scoped>
.login {
    max-width: 600px;
    margin: 0 auto;
    padding: 50px 20px;
}

.login-form {
    margin-bottom: 30px;
}

.router-link {
    display: block;
}

.router-link>.el-button {
    align-items: center;
    justify-content: center;
    display: inline-block;
    margin: 10px;
}
</style>
